package com.afu.doubleToken;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: TokenController
 * Package: com.afu.doubleToken
 * Description:
 *
 * @Author zxf
 * @Version 1.0
 */
@RestController
@RequestMapping("/Token")
public class TokenController {
    private ReflashToken reflashToken;
    private AccessToken accessToken;


    @GetMapping("/get")
    public List get() {
        reflashToken = new ReflashToken("刷新令牌", LocalDateTime.now().plusHours(24));
        accessToken = new AccessToken("访问令牌", LocalDateTime.now().plusHours(2));
        List resultList = new ArrayList();
        resultList.add(reflashToken);
        resultList.add(accessToken);
        return resultList;
    }

    @GetMapping("/protectSource")
    public String getProtectSource(@RequestParam("accessToken") String token) {
        return checkToken(token) ? "受保护资源" : "访问令失效";
    }


    @GetMapping("/reflashToken")
    public List reflashToken(@RequestParam("reflashToken") String reflashToken) {
        checkToken(reflashToken);
        return this.get();
    }


    private Boolean checkToken(String token) {
        try {
            LocalDateTime expireTime = accessToken.getExpireTime();
            return LocalDateTime.now().isBefore(expireTime);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
